<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑楼栋' : '新增楼栋（将会根据楼层数、单元数、每层户数自动生成单元和房户信息）'"
    width="900px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="140px"
      @submit.prevent
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="楼栋名称" prop="buildingName">
            <el-input
              v-model="formData.buildingName"
              placeholder="请输入楼栋名称"
              maxlength="50"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="楼栋编号" prop="buildingNo">
            <el-input
              v-model="formData.buildingNo"
              placeholder="请输入楼栋编号"
              maxlength="20"
              :disabled="isEdit"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="物业公司">
            <el-select
              v-model="formData.propertyCompanyId"
              placeholder="请选择物业公司"
              style="width: 100%"
              :disabled="isEdit"
              :clearable="!isEdit"
              @change="handlePropertyCompanyChange"
            >
              <el-option
                v-for="item in propertyCompanyOptions"
                :key="item.propertyCompanyId"
                :label="item.propertyCompanyName"
                :value="item.propertyCompanyId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="社区" prop="communityId">
            <el-select
              v-model="formData.communityId"
              placeholder="请选择社区"
              style="width: 100%"
              :disabled="!formData.propertyCompanyId"
              @change="handleCommunityChange"
            >
              <el-option
                v-for="item in communityOptions"
                :key="item.id"
                :label="item.communityName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="建筑类型" prop="buildingType">
            <el-select
              v-model="formData.buildingType"
              placeholder="请选择建筑类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in buildingTypeOptions"
                :key="item.id"
                :label="item.buildingTypeName"
                :value="item.buildingTypeName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12">
          <el-form-item label="楼层数" prop="floorCount">
            <el-input-number
              v-model="formData.floorCount"
              :min="1"
              :max="100"
              style="width: 100%"
              placeholder="请输入楼层数"
              :disabled="isEdit"
            />
            <div v-if="!isEdit" class="form-tip">请仔细检查,此项创建后不可更改</div>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="单元数" prop="unitCount">
            <el-input-number
              v-model="formData.unitCount"
              :min="1"
              :max="50"
              style="width: 100%"
              placeholder="请输入单元数"
              :disabled="isEdit"
            />
            <div v-if="!isEdit" class="form-tip">请仔细检查,此项创建后不可更改</div>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="每层户数" prop="unitsPerFloor">
            <el-input-number
              v-model="formData.unitsPerFloor"
              :min="1"
              :max="20"
              style="width: 100%"
              placeholder="请输入每层户数"
              :disabled="isEdit"
            />
            <div v-if="!isEdit" class="form-tip">请仔细检查,此项创建后不可更改</div>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
              <el-option :label="STATUS.ENABLED" :value="1" />
              <el-option :label="STATUS.DISABLED" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="地下层数" prop="undergroundFloor">
            <el-input-number
              v-model="formData.undergroundFloor"
              :min="0"
              :max="10"
              :step="1"
              :controls-position="'right'"
              placeholder="请输入地下层数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="结构类型" prop="structureType">
            <el-select
              v-model="formData.structureType"
              placeholder="请选择结构类型"
              style="width: 100%"
            >
              <el-option label="框架" :value="1" />
              <el-option label="剪力墙" :value="2" />
              <el-option label="砖混" :value="3" />
              <el-option label="钢结构" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="建设年份" prop="buildYear">
            <el-date-picker
              v-model="formData.buildYear"
              type="year"
              placeholder="请选择建设年份"
              style="width: 100%"
              value-format="YYYY"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="地下层数" prop="undergroundFloor">
            <el-input-number
              v-model="formData.undergroundFloor"
              :min="0"
              :max="10"
              :step="1"
              :controls-position="'right'"
              placeholder="请输入地下层数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="结构类型" prop="structureType">
            <el-select
              v-model="formData.structureType"
              placeholder="请选择结构类型"
              style="width: 100%"
            >
              <el-option label="框架" :value="1" />
              <el-option label="剪力墙" :value="2" />
              <el-option label="砖混" :value="3" />
              <el-option label="钢结构" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="建设年份" prop="buildYear">
            <el-date-picker
              v-model="formData.buildYear"
              type="year"
              placeholder="请选择建设年份"
              style="width: 100%"
              value-format="YYYY"
              format="YYYY"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="建筑面积" prop="area">
            <el-input-number
              v-model="formData.area"
              :min="0"
              :precision="2"
              :step="0.01"
              placeholder="请输入建筑面积(㎡)"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="占地面积" prop="landArea">
            <el-input-number
              v-model="formData.landArea"
              :min="0"
              :precision="2"
              :step="0.01"
              placeholder="请输入占地面积(㎡)"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="建筑高度" prop="buildingHeight">
            <el-input-number
              v-model="formData.buildingHeight"
              :min="0"
              :precision="2"
              :step="0.01"
              placeholder="请输入建筑高度(m)"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="是否有电梯" prop="hasElevator">
            <el-select
              v-model="formData.hasElevator"
              placeholder="请选择是否有电梯"
              style="width: 100%"
            >
              <el-option label="有" :value="1" />
              <el-option label="无" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="电梯数量" prop="elevatorCount">
            <el-input-number
              v-model="formData.elevatorCount"
              :min="0"
              :max="20"
              :step="1"
              placeholder="请输入电梯数量"
              style="width: 100%"
              :disabled="formData.hasElevator === 0"
            />
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入详细地址"
              maxlength="255"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="500"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 楼栋信息编辑表单
 * @author Wu.Liang
 * @date 2024-12-21
 */
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { buildingApi } from '@/api/building'
import { buildingFormRules } from '@/types/region'
import { useUserStore } from '@/store/user'
import { propertyInfoApi } from '@/api/property/propertyInfo'
import { buildingTypeApi } from '@/api/buildingType'
import { propertyCompanyApi } from '@/api/property/propertyCompany'

// 定义props
interface Props {
  visible: boolean
  building?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  building: undefined
})

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)
const userStore = useUserStore()

// 表单数据
const formData = reactive({
  buildingName: '',
  buildingNo: '',
  buildingType: undefined as string | undefined,
  communityId: undefined as number | undefined,
  propertyCompanyId: undefined as number | undefined,
  floorCount: 1,
  unitCount: 1,
  unitsPerFloor: 2,
  status: 1,
  remark: '',
  undergroundFloor: 0,
  structureType: 1,
  buildYear: undefined as number | undefined,
  area: 0,
  landArea: 0,
  buildingHeight: 0,
  hasElevator: 1,
  elevatorCount: 0,
  address: ''
})

// 选项数据
const propertyCompanyOptions = ref<any[]>([])
const communityOptions = ref<any[]>([])
const buildingTypeOptions = ref<any[]>([])

// 表单验证规则
const rules: FormRules = {
  buildingName: [
    { required: true, message: '请输入楼栋名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  buildingNo: [
    { required: true, message: '请输入楼栋编号', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  communityId: [
    { required: true, message: '请选择所属社区', trigger: 'change' }
  ],
  buildingType: [
    { required: true, message: '请选择建筑类型', trigger: 'change' }
  ],
  floorCount: [
    { required: true, message: '请输入楼层数', trigger: 'blur' },
    { type: 'number', min: 1, max: 200, message: '楼层数必须在1-200之间', trigger: 'blur' }
  ],
  unitCount: [
    { required: true, message: '请输入单元数', trigger: 'blur' },
    { type: 'number', min: 1, max: 50, message: '单元数必须在1-50之间', trigger: 'blur' }
  ],
  unitsPerFloor: [
    { required: true, message: '请输入每层户数', trigger: 'blur' },
    { type: 'number', min: 1, max: 20, message: '每层户数必须在1-20之间', trigger: 'blur' }
  ]
}

// 状态常量
const STATUS = {
  ENABLED: '启用',
  DISABLED: '禁用'
}

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.building?.id)

// 获取物业公司列表
const loadPropertyCompanyList = async () => {
  try {
    const currentUserId = userStore.userInfo?.id
    if (!currentUserId) {
      console.error('用户信息不存在，无法获取物业公司列表')
      return
    }
    
    const response = await propertyInfoApi.getUserPropertyCompanies(currentUserId)
    if (response.code === 200 && response.data) {
      propertyCompanyOptions.value = response.data
      // 默认选中第一个物业公司
      if (propertyCompanyOptions.value.length > 0 && !formData.propertyCompanyId) {
        formData.propertyCompanyId = propertyCompanyOptions.value[0].propertyCompanyId
        // 加载对应的社区列表
        await loadCommunityList(formData.propertyCompanyId)
      }
    } else {
      propertyCompanyOptions.value = []
      console.warn('获取物业公司列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取物业公司列表失败:', error)
    propertyCompanyOptions.value = []
  }
}

// 获取社区列表
const loadCommunityList = async (propertyCompanyId: number) => {
  if (!propertyCompanyId) {
    communityOptions.value = []
    return
  }
  
  try {
    const response = await propertyCompanyApi.getAssignedCommunities(propertyCompanyId)
    if (response.code === 200 && response.data) {
      communityOptions.value = response.data
    } else {
      communityOptions.value = []
      console.warn('获取社区列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取社区列表失败:', error)
    communityOptions.value = []
  }
}

// 获取平台公共建筑类型列表
const loadBuildingTypeList = async () => {
  try {
    const response = await buildingTypeApi.getPublicBuildingTypes()
    if (response.code === 200 && response.data) {
      buildingTypeOptions.value = response.data
    } else {
      buildingTypeOptions.value = []
      console.warn('获取建筑类型列表失败:', response.message)
    }
  } catch (error) {
    console.error('获取建筑类型列表失败:', error)
    buildingTypeOptions.value = []
  }
}

// 处理物业公司变化
const handlePropertyCompanyChange = async (propertyCompanyId: number) => {
  // 清空社区选择
  formData.communityId = undefined
  
  // 加载对应的社区列表
  await loadCommunityList(propertyCompanyId)
}

// 处理社区变化
const handleCommunityChange = async (communityId: number) => {
  // 社区变化时不需要特殊处理，建筑类型是平台公共的
}

// 重置表单
const resetForm = () => {
  formData.buildingName = ''
  formData.buildingNo = ''
  formData.buildingType = undefined
  formData.communityId = undefined
  formData.propertyCompanyId = undefined
  formData.floorCount = 1
  formData.unitCount = 1
  formData.unitsPerFloor = 2
  formData.status = 1
  formData.remark = ''
  formData.undergroundFloor = 0
  formData.structureType = 1
  formData.buildYear = undefined
  formData.area = 0
  formData.landArea = 0
  formData.buildingHeight = 0
  formData.hasElevator = 1
  formData.elevatorCount = 0
  formData.address = ''
  formRef.value?.clearValidate()
}

// 填充表单数据
const fillFormData = (building: any) => {
  formData.buildingName = building.buildingName || ''
  formData.buildingNo = building.buildingNo || ''
  formData.buildingType = building.buildingType || undefined
  formData.communityId = building.communityId
  formData.propertyCompanyId = undefined // 编辑时不设置物业公司ID，需要用户重新选择
  formData.floorCount = Number(building.floorCount) || 1
  formData.unitCount = Number(building.unitCount) || 1
  formData.unitsPerFloor = Number(building.unitsPerFloor) || 2
  formData.status = building.status !== undefined ? Number(building.status) : 1
  formData.remark = building.remark || ''
  formData.undergroundFloor = Number(building.undergroundFloor) || 0
  formData.structureType = Number(building.structureType) || 1
  formData.buildYear = building.buildYear || undefined
  formData.area = Number(building.area) || 0
  formData.landArea = Number(building.landArea) || 0
  formData.buildingHeight = Number(building.buildingHeight) || 0
  formData.hasElevator = building.hasElevator !== undefined ? Number(building.hasElevator) : 1
  formData.elevatorCount = Number(building.elevatorCount) || 0
  formData.address = building.address || ''
  
  // 编辑模式下，需要根据社区ID获取对应的物业公司ID来加载建筑类型列表
  if (building.communityId) {
    // 这里可以通过社区ID获取对应的物业公司ID，然后加载建筑类型列表
    // 暂时先不实现，用户需要手动选择物业公司来获取建筑类型
  }
}

// 监听对话框显示状态和楼栋数据变化
watch(() => props.visible, (newVisible) => {
  if (newVisible && isEdit.value && props.building?.id) {
    // 编辑模式且对话框打开时，直接使用传入的楼栋数据填充表单
    fillFormData(props.building)
  } else if (newVisible && !isEdit.value) {
    // 新增模式时，重置表单并加载物业公司列表
    resetForm()
    loadPropertyCompanyList()
  }
}, { immediate: true })

// 监听楼栋数据变化（直接传入楼栋数据的情况）
watch(() => props.building, (newBuilding) => {
  if (props.visible && isEdit.value && newBuilding?.id) {
    fillFormData(newBuilding)
  }
}, { deep: true })

// 组件挂载时加载物业公司列表
onMounted(() => {
  // 加载平台公共建筑类型列表
  loadBuildingTypeList()
})

// 监听电梯选择变化
watch(() => formData.hasElevator, (newValue) => {
  if (newValue === 0) {
    formData.elevatorCount = 0
  }
})

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData: any = {}
    
    if (formData.buildingName) submitData.buildingName = formData.buildingName
    if (formData.buildingNo) submitData.buildingNo = formData.buildingNo
    if (formData.buildingType !== undefined) submitData.buildingType = formData.buildingType
    if (formData.communityId !== undefined) submitData.communityId = formData.communityId
    if (formData.floorCount) submitData.floorCount = formData.floorCount
    if (formData.unitCount) submitData.unitCount = formData.unitCount
    if (formData.unitsPerFloor) submitData.unitsPerFloor = formData.unitsPerFloor
    if (formData.status !== undefined) submitData.status = Number(formData.status)
    if (formData.remark) submitData.remark = formData.remark
    if (formData.undergroundFloor !== undefined) submitData.undergroundFloor = Number(formData.undergroundFloor)
    if (formData.structureType !== undefined) submitData.structureType = Number(formData.structureType)
    if (formData.buildYear) submitData.buildYear = formData.buildYear
    if (formData.area !== undefined) submitData.area = Number(formData.area)
    if (formData.landArea !== undefined) submitData.landArea = Number(formData.landArea)
    if (formData.buildingHeight !== undefined) submitData.buildingHeight = Number(formData.buildingHeight)
    if (formData.hasElevator !== undefined) submitData.hasElevator = Number(formData.hasElevator)
    if (formData.elevatorCount !== undefined) submitData.elevatorCount = Number(formData.elevatorCount)
    if (formData.address) submitData.address = formData.address
    
    // 注意：不提交propertyCompanyId，因为楼栋通过社区间接关联物业公司
    
    let response
    if (isEdit.value) {
      response = await buildingApi.updateBuilding(props.building.id, submitData)
    } else {
      response = await buildingApi.createBuilding(submitData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      emit('update:visible', false)
    } else {
      ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.field-tip {
  display: flex;
  align-items: center;
  margin-top: 5px;
  color: #909399;
  font-size: 12px;

  .el-icon {
    margin-right: 5px;
  }
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}
</style> 